var teach;

function Teach(groups) {
  this.groups = groups;
  this.tab = "members";
}

Teach.prototype = {

  start : function() {
    var select = $("select#group").html("");
    var grps = this.groups;
    if (grps.length > 0) {
      for (var i = 0; i < grps.length; i++) {
        var grp = grps[i];
        select.append("<option value='" + grp.id +"'>" + grp.name + "</option>");
      }
      var hash = window.location.hash;
      if (hash.length > 0) {
        this.handleHash(hash);
      } else {
        window.location.hash = grps[0].id;
      }
    } else {
      select.append("<option>No groups yet.</option>");
    }
    select.append("<optgroup label='----------------'></optgroup><option value='new'>Create new group</option>");
    select.change(this.group.change);
    var g = this.group.getById(select.val());
    this.members.show(g);
    this.assignments.show(g);
    $("a[href=#members]").click(this, function(event) {
      var t = event.data;
      var active = t.group.getActive();
      if (active) {
        window.location.hash = active.id + "m";
        t.tab = "members";
      }
    });
    $("a[href=#assignments]").click(this, function(event) {
      var t = event.data;
      var active = t.group.getActive();
      if (active) {
        window.location.hash = active.id + "a";
        t.tab = "assignments";
      }
    });
  },

  handleHash : function(hash) {
    $("select#group").find("option[value=" + hash.substring(1,9) + "]").attr("selected", "selected");
    if (hash.length > 9 && hash.charAt(9) == "a") {
      $("a[href=#assignments]").click();
    }
  },

  group : {
    change : function(event) {
      var id = $(event.target).val();
      if (id == "new") {
        teach.group.create();
      } else {
        var g = teach.group.getById(id);
        teach.members.show(g);
        teach.assignments.show(g);
        window.location.hash = id + teach.tab.charAt(0);
      }
    },

    create : function() {
      var width = 480;
      var cg = $("#create_group");
      cg.dialog({ title : "Create Group", resizable : false, modal : true,
        position : [0.5 * ($(window).width() - width), 80], width : width, height : 120,
        close : function() {
          teach.handleHash(window.location.hash);
        }
      }).dialog("open");
      cg.find("button").button().click(cg, this.create2);
    },

    create2 : function(event) {
      var cg = event.data;
      var name = cg.find(".name").val();
      if (name.length < 4) {
        cg.find(".min_length").show();
        cg.find(".name").focus();
        return;
      }
      $.ajax({
        url : "/teach/create_group?name=" + name,
        type : "post",
        success : function(response) {
          if (response.length > 0) { alert(response); }
          window.location.reload(true);
        }
      });
    },

    getActive : function() {
      return this.getById($("select#group").val());
    },

    getById : function(group_id) {
      var grps = teach.groups;
      for (var i = 0; i < grps.length; i++) {
        if (grps[i].id == group_id) {
          return grps[i];
        }
      }
    }
  },

  members : {
    show : function(group) {
      var ml = $("#member_list");
      if (!group) {
        ml.html("Create a group to use this tab.");
        return;
      }
      var members = group.members;
      if (members.length == 0) {
        ml.html("This group has no members.");
        $("button#edit_members").hide();
        return;
      }
      var table = "<table><tr><th style='width:25%;'>First name</th><th style='width:25%;'>Last name</th>" +
        "<th style='width:50%;'></th></tr>";
      for (var j = 0; j < members.length; j++) {
        var m = members[j];
        if (m.active) {
          table += "<tr><td>" + m.first_name + "</td><td>" + m.last_name + "</td><td></td></tr>";
        }
      }
      table += "</table>";
      ml.html(table);
      $("button#edit_members").show();
    },

    edit : function() {
      var members = teach.group.getActive().members;
      var table = "<table><tr><th style='width:20%;'>First name</th><th style='width:20%;'>Last name</th>" +
        "<th style='width:50%;'></th></tr>";
      for (var i = 0; i < members.length; i++) {
        var m = members[i];
        if (m.active) {
          var onclick = "deleteMember(" + i + ");";
          table += "<tr><td><input type='text' name='first' value='" + m.first_name + "' i='" + i + "' /></td>" +
                  "<td><input type='text' name='last' value='" + m.last_name + "' i='" + i + "' /></td>" +
                  "<td><a onclick='" + onclick + "'>x</a></td></tr>";
        }
      }
      table += "</table>";
      $("#member_list").html(table);
      $("button#edit_members").hide();
      $("button#save_changes").show();
    },

    add : function() {
      this.update();
      teach.group.getActive().members.push({first_name : "", last_name : "", active : true });
      this.edit();
    },

    save : function() {
      this.update();
      var group = teach.group.getActive();
      $.post( "/teach/update_group", { group_json : JSON.stringify(group) },
        function(response) {
          if (response.length > 0) { alert(response) }
          window.location.reload(true);
        }
      );
      $("button#save_changes").hide();
      $("button#edit_members").show();
      this.show(group);
    },

    update : function() {
      var group = teach.group.getActive();
      $.each($("#member_list input"), function(i, n) {
        var m = $(n);
        var member = group.members[m.attr("i")];
        switch (m.attr("name")) {
          case "first" : member.first_name = m.val(); break;
          case "last"  : member.last_name = m.val(); break;
        }
      });
    }
  },

  assignments : {
    show : function(group) {
      var al = $("#assignment_list");
      if (!group) {
        al.html("Create a group to use this tab.");
        return;
      }
      var ants = group.assignments;
      if (ants.length == 0) {
        al.html("This group has no assignments.");
        return;
      }
      var table = "<table style='width:400px;'><tr>";
      for (var i = 0; i < ants.length; i++) {
        var a = ants[i];
        var onclick = "teach.assignments.showDetails('" + a.id + "');";
        table += "<td><button onclick=\"" + onclick + "\">" + a2a[a.lab] + "</button></td>";
      }
      table += "</tr></table>";
      al.html(table);
      al.find("button").button();
    },

    showDetails : function(id) {
      $.ajax({
        url : "/teach/assignment?id=" + id,
        success : function(response) {
          var width = 800;
          $("#show_assignment").html(response).dialog({ title : "Assignment Details", resizable : false, modal : true,
            position : [0.5 * ($(window).width() - width), 80], width : width, height : 320 });
        }
      });
    },

    create : function() {
      var width = 360;
      $('#create_assignment').dialog({ title : "New Assignment", resizable : false, modal : true,
        position : [0.5 * ($(window).width - width), 80], width : width, height : 120 }).dialog('open');
    },

    create2 : function() {
      var ca = $("#create_assignment");
      var lab = ca.find("select").val();
      $.post("/teach/create_assignment", { "group_id" : teach.group.getActive().id, "lab" : lab },
        function(response) {
          if (response.length > 0) { alert(response); }
          window.location.reload(true);
        }
      );
    }
  }
};